import React, { useCallback, useEffect, useMemo, useState } from 'react';
import styled from './index.module.css';
import CategoryList from '../components/category/categoryList';
import { useFetchCategory } from './useFetchCategory';
import MyCarousel from './components/carousel/myCarousel';
import { getCategory } from '@/api/category';
import { Good, GoodCategory, IPagination, PaginateReturn } from '../types';
import { fetchBanners, getGoodList } from '@/api/good';
import { IBannerList, ICart } from './types';
import GoodItem from './components/goodItem/goodItem';
import { Pagination, message } from 'antd';
import usePagination from './components/usePagination';
import { useNavigate } from 'react-router-dom/dist/index';
import { fetchCreateOrUpdateCarts } from '@/api/cart';
import { IResponse } from '@/types';

export default function Goods() {
    const [curCategory, setCurCategory] = useState<string>('');
    const nav = useNavigate();
    const { data: category, fetchData: fetchCategory } = useFetchCategory<any, GoodCategory[]>(
        getCategory,
    );
    const { data: banners, fetchData: getBanners } = useFetchCategory<any, IBannerList[]>(
        fetchBanners,
    );
    const {
        data: goods,
        fetchData: getGoods,
        total,
    } = useFetchCategory<IPagination, PaginateReturn<Good>>(getGoodList);
    const filter_params = useMemo<IPagination>(() => {
        const params = new URLSearchParams(window.location.search);
        const values: any = {};
        for (let key of params.keys()) {
            if (key === 'category') {
                setCurCategory(params.get(key) || '');
            }
            values[key] = params.get(key);
        }
        return {
            pageNumber: 1,
            pageSize: 10,
            categoryId: '',
            ...values,
        };
    }, []);

    const {
        onChange: paginationChange,
        current: curPage,
        setCurrent: setPage,
    } = usePagination(filter_params, getGoods);

    useEffect(() => {
        fetchCategory();
        getBanners();
        getGoods({
            ...filter_params,
        });
    }, []);
    const urlChange = useCallback((id: string) => {
        setPage(1);
        getGoods({
            ...filter_params,
            category: id,
            pageNumber: 1,
        });
    }, []);
    const goDetailProp = useCallback((good: Good) => {
        nav(`/goods/detail/${good.id}/${good.categories[0].id}`);
    }, []);
    const addcart = useCallback((good: Good) => {
        fetchCreateOrUpdateCarts<ICart, IResponse>({
            good: good.id,
            num: 1,
            is_select: false,
        }).then((res) => {
            if (res.statusCode === 200) {
                message.success('添加成功');
            } else if (res.statusCode === 403) {
                localStorage.setItem('cur_good', JSON.stringify(good));
            } else {
                message.error('添加失败');
            }
        });
    }, []);
    return (
        <div className={styled.goods}>
            <CategoryList
                urlChange={urlChange}
                cur={curCategory}
                categories={category || []}
            ></CategoryList>
            <MyCarousel banners={banners}></MyCarousel>
            <div className={styled.good_list}>
                {goods.items
                    ? goods.items.map((item: Good) => {
                          return (
                              <GoodItem
                                  addCartProp={addcart}
                                  goDetailProp={goDetailProp}
                                  key={item.id}
                                  good={item}
                              ></GoodItem>
                          );
                      })
                    : null}
            </div>
            <Pagination
                style={{ padding: '20px 0' }}
                current={curPage}
                onChange={paginationChange}
                total={total}
            />
        </div>
    );
}
